package com.help10000.rms.ui.activitys

import android.content.Context
import android.content.Intent
import android.net.http.SslError
import android.os.Bundle
import android.webkit.*
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.mvp.view.IView
import com.help10000.rms.R
import com.help10000.rms.ui.base.BaseActivity
import kotlinx.android.synthetic.main.activity_open_url.*

class OpenUrlActivity : BaseActivity<BasePresenter<IView>, IView>() {
    private var url: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    companion object {
        fun startActivity(context: Context, url: String) {
            var intent = Intent(context, OpenUrlActivity::class.java)
            intent.putExtra("url", url)
            context.apply {
                startActivity(intent)
            }
        }
    }

    override fun getlayoutId(): Int {
        return R.layout.activity_open_url
    }

    override fun initView() {
        url = intent.getStringExtra("url")
        if (url.isNullOrBlank())
            finish()
        else
            urlWebView.loadUrl(url!!)
        showLoading()
        urlWebView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, webTitle: String?) {
                pageTitleBar.setTitle(webTitle)
            }

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
            }

        }
        urlWebView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                dismissLoading()
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
                dismissLoading()
                val data = "网页加载失败！"
                view!!.loadUrl("javascript:document.body.innerHTML=\"$data\"")
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                dismissLoading()
                val data = "网页加载失败！"
                view!!.loadUrl("javascript:document.body.innerHTML=\"$data\"")
            }
        }
        pageTitleBar.setOnLeftClickListener {
            onBackPressed()
        }

    }

    override fun onBackPressed() {
        if (urlWebView.canGoBack())
            urlWebView.goBack();
        else
            super.onBackPressed()
    }

    override fun initData(savedInstanceState: Bundle?) {

    }
}